package com.sikaryofficial.backend.service.email;

import com.sikaryofficial.backend.constant.EmailConstant;
import com.sikaryofficial.backend.service.INoticeLogService;
import com.sikaryofficial.common.core.utils.ip.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author : qinjinyuan
 * @desc : 邮件发送服务实现类
 * @date : 2023/10/28 16:51
 */
@Service(value = EmailConstant.NORMAL_SENDER + EmailConstant.SUFFIX)
@Slf4j
public class EmailServiceImpl implements EmailService {

    private static final Integer SUCCESS = 0;
    private static final Integer FAIL = 1;
    /**
     * Spring Boot 提供了一个发送邮件的简单抽象，使用的是下面这个接口，这里直接注入即可使用
     */
    @Resource(name = "normalSender")
    private JavaMailSender mailSender;
    /**
     * 配置文件中我的qq邮箱
     */
    @Value("${spring.mail.from}")
    private String from;
    @Autowired
    private INoticeLogService noticeLogService;

    /**
     * 简单文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        long startTime = System.currentTimeMillis();
        String ip = IpUtils.getIpAddr();
        try {
            //创建SimpleMailMessage对象
            SimpleMailMessage message = new SimpleMailMessage();
            //邮件发送人
            message.setFrom(from);
            //邮件接收人
            message.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容
            message.setText(content);
            //发送邮件
            mailSender.send(message);
            // 记录发送日志
            noticeLogService.saveEmailLog(System.currentTimeMillis() - startTime, content, to, SUCCESS, ip);
            log.info("normal 邮件已经发送。from:{}",from);
        } catch (Exception e) {
            log.error("发送邮件时发生异常！", e);
            noticeLogService.saveEmailLog(System.currentTimeMillis() - startTime, content, to, FAIL, ip);
        }
    }

    /**
     * html邮件
     *
     * @param to      收件人,多个时参数形式 ："xxx@xxx.com,xxx@xxx.com,xxx@xxx.com"
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        long startTime = System.currentTimeMillis();
        String ip = IpUtils.getIpAddr();
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(from);
            //邮件接收人,设置多个收件人地址
            InternetAddress[] internetAddressTo = InternetAddress.parse(to);
            messageHelper.setTo(internetAddressTo);
            //邮件主题
            message.setSubject(subject);
            //邮件内容，html格式
            messageHelper.setText(content, true);
            //发送
            mailSender.send(message);
            // 记录发送日志
            noticeLogService.saveEmailLog(System.currentTimeMillis() - startTime, content, to, SUCCESS, ip);
            log.info("normal 邮件已经发送。from:{}",from);
        } catch (Exception e) {
            log.error("发送邮件时发生异常！", e);
            noticeLogService.saveEmailLog(System.currentTimeMillis() - startTime, content, to, FAIL, ip);
        }
    }

    /**
     * 带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        long startTime = System.currentTimeMillis();
        String ip = IpUtils.getIpAddr();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            //日志信息
            noticeLogService.saveEmailLog(System.currentTimeMillis() - startTime, content, to, SUCCESS, ip);
            log.info("normal 邮件已经发送。from:{}",from);
        } catch (Exception e) {
            log.error("发送邮件时发生异常！", e);
            noticeLogService.saveEmailLog(System.currentTimeMillis() - startTime, content, to, FAIL, ip);
        }
    }
}